package com.XZDP.utils.LOCK;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class ILOCKlmpl implements ILOCK {
    private StringRedisTemplate redisTemplate;
    //公共前缀
    private static final String KEY_PREFIX = "Lock";
    //传入的锁名字,按照业务名定制
    private String name;
    private String uid = UUID.randomUUID().toString();

    public ILOCKlmpl(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public Boolean TryGetLock(Long timeout) {
        String value = uid + Thread.currentThread().getId();
        Boolean success = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, value, timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void CloseLock() {
        //释放的时候比对和原来的是否是一个锁
        //获取当前锁特征值
        String nowValue = uid + Thread.currentThread().getId();
        //获取redis中的值
        String s = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (s.equals(nowValue)) {
            //确定是同一个锁对象进行删除
            redisTemplate.delete(KEY_PREFIX + name);
        }
    }
}
